<script setup>
import { ref, onMounted } from 'vue'
import {
    ElTable,ElTableColumn,ElButton,ElDialog,
    ElForm,ElFormItem,ElInput,ElSelect,ElOption,
    ElMessageBox,ElMessage
} from 'element-plus'
import { getCategoryList, addCategory, updateCategory, deleteCategory } from '@/api/category'

// 分类列表数据
const categoryList = ref([])
const loading = ref(false)

// 选中项管理
const selectedIds = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('新增分类')

// 分类表单数据
const categoryForm = ref({
    id: null,
    parentId: 0,
    name: '',
    level: 0,
    description: '',
    version: 1
})

// 表单验证规则
const formRules = ref({
    name: [
        { required: true, message: '分类名称不能为空', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
    ],
    parentId: [
        { required: true, message: '父级分类不能为空', trigger: 'change' }
    ]
})

// 获取分类数据
const fetchCategoryList = async () => {
    const result = await getCategoryList()
    console.log('原始分类数据：', result.data)
    categoryList.value = buildTree(result.data)
    console.log("构建树形数据后：",categoryList.value);
    
}

// 构建树形数据
const buildTree = (data, parentId = 0, level = 0) => {
    return data
        .filter(item => item.parentId == parentId) // 修正字段名
        .map(item => ({
            ...item,
            level: level, // 同步 level 字段
            children: buildTree(data, item.id, level + 1)
        }))
}

// 打开新增弹窗
const openAddDialog = () => {
    isEdit.value = false
    dialogTitle.value = '新增分类'
    categoryForm.value = {
        id: null,
        parentId: 0,
        name: '',
        level: 0,
        description: '',
        version: 1
    }
    dialogVisible.value = true
}

// 打开编辑弹窗
const openEditDialog = (row) => {
    isEdit.value = true
    dialogTitle.value = '编辑分类'
    categoryForm.value = { ...row }
    dialogVisible.value = true
}

// 删除分类
const handleDelete = (id) => {
    // 检查是否有子分类
    const item = findCategoryById(categoryList.value, id)
    if (item?.children?.length > 0) {
        selectedIds.value = [id, ...item.children.map(child => child.id)]
        handleBatchDelete()
    } else {
        ElMessageBox.confirm('此操作将永久删除该分类, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteCategory(id)
        ElMessage.success('删除成功!')
        fetchCategoryList()
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
    }   
}

// 批量删除
const handleBatchDelete = () => {
    ElMessageBox.confirm(
        `确认删除 ${selectedIds.value.length} 个分类？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            // 反复调用删除接口
            for (let i = 0; i < selectedIds.value.length; i++) {
                await deleteCategory(selectedIds.value[i])
            }
            ElMessage.success('批量删除成功!')
            // 清空选中项
            selectedIds.value = []
            // 刷新列表
            fetchCategoryList()
        } catch (error) {
            ElMessage.error('批量删除失败')
            console.error('批量删除错误:', error)
        }
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

// 根据ID查找分类
const findCategoryById = (data, id) => {
    for (const item of data) {
        if (item.id === id) return item
        if (item.children) {
            const found = findCategoryById(item.children, id)
            if (found) return found
        }
    }
    return null
}

// 处理多选变化
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id)
}

// 保存分类
const saveCategory = async () => {
    try {
        if (isEdit.value) {
            await updateCategory(categoryForm.value)
            ElMessage.success('更新成功!')
        } else {
            await addCategory(categoryForm.value)
            ElMessage.success('新增成功!')
        }
        dialogVisible.value = false
        fetchCategoryList()
    } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
        console.error('操作错误:', error)
    }
}

// 组件挂载时获取数据
onMounted(() => {
    fetchCategoryList()
})
</script>

<template>
    <div class="category-container">
        <!-- 头部操作区 -->
        <div class="header">
            <h2>分类管理</h2>

            <div class="header-actions">
                <el-button type="primary" @click="openAddDialog">新增分类</el-button>
                <el-button type="danger" @click="handleBatchDelete"
                    :disabled="selectedIds.length === 0">批量删除</el-button>
            </div>
        </div>


        <!-- 分类表格 -->
        <el-table :data="categoryList" row-key="id" border default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="分类名称" min-width="200">
                <template #default="scope">
                    <span v-if="scope.row.is_deleted === 1" style="text-decoration: line-through;">
                        {{ scope.row.name }}
                    </span>
                    <span v-else>{{ scope.row.name }}</span>
                </template>
            </el-table-column>

            <el-table-column prop="icon" label="图标" width="70" align="center">
                <template #default="scope">
                    <span style="font-size: 25px;">
                        {{ scope.row.icon || '🈚' }}
                    </span>
                    
                </template>
            </el-table-column>

            <el-table-column prop="level" label="分类级别" width="120" align="center">
                <template #default="scope">
                    {{ scope.row.level === 0 ? '一级分类' : '二级分类' }}
                </template>
            </el-table-column>

            <!-- <el-table-column prop="parentId" label="父级分类ID" width="120" align="center">
                <template #default="scope">
                    {{ scope.row.parentId || '-' }}
                </template>
            </el-table-column> -->

            <el-table-column prop="description" label="描述信息" min-width="200">
                <template #default="scope">
                    {{ scope.row.description || '-' }}
                </template>
            </el-table-column>

            <el-table-column label="状态" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.is_deleted === 1 ? 'danger' : 'success'" size="small">
                        {{ scope.row.is_deleted === 1 ? '已删除' : '正常' }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="180" align="center">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分类弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
            <el-form :model="categoryForm" :rules="formRules" label-width="100px">
                <el-form-item label="父级分类" prop="parentId">
                    <el-select v-model="categoryForm.parentId" placeholder="请选择" style="width: 100%">
                        <el-option label="一级分类" :value="0" />
                        <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="categoryForm.name" />
                </el-form-item>

                <el-form-item label="描述信息" prop="description">
                    <el-input v-model="categoryForm.description" type="textarea" :rows="3" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveCategory">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.category-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.header h2 {
    margin: 0;
}
</style>